Option Explicit

Const WORKER_MACRO_NAME As String = "RunWorkerLog" ' 修改 Worker 宏名称以反映新功能
Const SIMULATED_QUERY_TIME As String = "00:00:05" ' 模拟查询耗时
Const MARKER_FILE_EXT As String = ".tmp" ' 标记文件扩展名

' --- 主控制宏 ---
Sub Main_ParallelDBQuery()
    Dim ws As Worksheet
    Dim fso As Object ' FileSystemObject
    Dim wsh As Object ' WScript.Shell
    Dim mainWorkbookPath As String
    Dim mainWorkbookName As String
    Dim workerFileName As String
    Dim scriptFileName As String
    Dim markerFileName As String
    Dim vbsCode As String
    Dim numberOfWorkers As Integer
    Dim nWorker As Integer
    ' Dim lastRow As Long ' 不再需要
    ' Dim startRow As Long ' 不再需要
    ' Dim endRow As Long ' 不再需要
    ' Dim rowsPerWorker As Long ' 不再需要
    Dim allWorkersFinished As Boolean
    Dim workerScripts As Object
    Dim startTime As Double
    Dim key As Variant
    Dim originalInteractiveState As Boolean ' 保存原始状态
    Dim resultsFilePath As String ' To store path of result file
    Dim processedWorkers As Object ' <--- 新增: 跟踪已处理的 Worker
    ' Dim key As Variant             ' <--- 移到这里，因为循环中会用到  <--- 删除这行重复声明
    
    startTime = Timer
    On Error GoTo ErrorHandler

    originalInteractiveState = Application.Interactive ' 保存当前交互状态
    Application.Interactive = False ' 禁止用户交互
    Application.ScreenUpdating = False ' 同时建议关闭屏幕更新提高性能

    Set ws = ThisWorkbook.Sheets("Sheet1")
    mainWorkbookPath = ThisWorkbook.Path
    mainWorkbookName = ThisWorkbook.Name

    ' 获取要模拟的并行任务数 (工人数量)
    numberOfWorkers = Application.InputBox("请输入要模拟的并行 Worker 数量:", "并行数量", 2, Type:=1)
    If numberOfWorkers <= 0 Then Exit Sub

    ' 清除旧结果 (A1 到 C[N+1])
    ws.Range("A1:C" & numberOfWorkers + 1).ClearContents
    ws.Range("A1").Value = "主线程: 准备中, 开始时间: " & Format(Now, "hh:mm:ss")

    ' --- 移除计算行相关的代码 ---
    ' lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    ' If lastRow < 2 Then
    '     MsgBox "Sheet1 A列没有需要查询的数据 (从 A2 开始)。", vbInformation
    '     Exit Sub
    ' End If
    ' rowsPerWorker = Application.WorksheetFunction.RoundUp((lastRow - 1) / numberOfWorkers, 0)

    ' 创建 FileSystemObject 和 WScript.Shell
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set wsh = CreateObject("WScript.Shell")
    Set workerScripts = CreateObject("Scripting.Dictionary")
    Set processedWorkers = CreateObject("Scripting.Dictionary") ' <--- 初始化移到这里
    Dim Results_Map As Object ' <--- 确保已声明
    Dim resultData As Variant ' <--- 建议将 Dim 移到 Sub 顶部

    ws.Range("A1").Value = "主线程: 创建副本和脚本..."

    ' --- 预先清理可能存在的旧临时文件 (包括结果文件) ---
    Call CleanupWorkerFiles(fso, mainWorkbookPath, numberOfWorkers)

    ' --- 循环创建副本和 VBS 脚本 (代码不变) ---
    For nWorker = 1 To numberOfWorkers
        ' --- 移除计算行相关的代码 ---
        ' startRow = (nWorker - 1) * rowsPerWorker + 2
        ' endRow = Application.WorksheetFunction.Min(startRow + rowsPerWorker - 1, lastRow)
        ' If startRow > lastRow Then Exit For

        ' 1. 保存工作簿副本 (.xlsm)
        workerFileName = mainWorkbookPath & "\~Worker_" & numberOfWorkers & "_" & nWorker & ".xlsm"
        ThisWorkbook.SaveCopyAs workerFileName

        ' 2. 准备 VBS 脚本内容 (调用新的 Worker 宏)
        scriptFileName = mainWorkbookPath & "\~Worker_" & numberOfWorkers & "_" & nWorker & ".vbs"
        markerFileName = mainWorkbookPath & "\~Worker_" & numberOfWorkers & "_" & nWorker & MARKER_FILE_EXT

        vbsCode = "On Error Resume Next" & vbCrLf & _
                  "Dim objExcel, objWorkbook, fso, ts" & vbCrLf & _
                  "Set objExcel = CreateObject(""Excel.Application"")" & vbCrLf & _
                  "If Err.Number <> 0 Then WScript.Quit" & vbCrLf & _
                  "objExcel.Visible = False" & vbCrLf & _
                  "Set objWorkbook = objExcel.Workbooks.Open(""" & workerFileName & """)" & vbCrLf & _
                  "If Err.Number <> 0 Then" & vbCrLf & _
                  "  objExcel.Quit" & vbCrLf & _
                  "  Set objExcel = Nothing" & vbCrLf & _
                  "  WScript.Quit" & vbCrLf & _
                  "End If" & vbCrLf & _
                  "' 运行工作宏，传递参数：工人编号, 主工作簿名" & vbCrLf & _
                  "objExcel.Application.Run ""'" & fso.GetFileName(workerFileName) & "'!" & WORKER_MACRO_NAME & """," & nWorker & ",""" & mainWorkbookName & """" & vbCrLf & _
                  "objWorkbook.Close False ' 关闭副本，不保存更改" & vbCrLf & _
                  "objExcel.Quit" & vbCrLf & _
                  "Set objWorkbook = Nothing" & vbCrLf & _
                  "Set objExcel = Nothing" & vbCrLf & _
                  "' *** 新增：创建标记文件 ***" & vbCrLf & _
                  "Set fso = CreateObject(""Scripting.FileSystemObject"")" & vbCrLf & _
                  "Set ts = fso.CreateTextFile(""" & markerFileName & """, True)" & vbCrLf & _
                  "If Err.Number = 0 Then ts.Close" & vbCrLf & _
                  "Set ts = Nothing" & vbCrLf & _
                  "Set fso = Nothing" & vbCrLf & _
                  "On Error GoTo 0"

        ' 3. 保存 VBS 脚本文件
        Call WriteTextFile(fso, scriptFileName, vbsCode)
        workerScripts.Add nWorker, markerFileName

        ' 4. 异步执行 VBS 脚本
        wsh.Run """" & scriptFileName & """", 0, False

        DoEvents
    Next nWorker

    ws.Range("A1").Value = "主线程: " & workerScripts.Count & " 个 Worker 已启动，等待完成和处理结果..."
    Application.StatusBar = "等待 " & workerScripts.Count & " 个后台 Worker 完成..."

    ' --- 等待所有 Worker 完成并处理结果 ---
    Dim waitStartTime As Double
    Dim timeoutSeconds As Long
    Dim pauseUntil As Double
    waitStartTime = Timer
    timeoutSeconds = 60 ' 设置超时时间

    Do
        ' --- 修改等待逻辑 ---
        allWorkersFinished = True ' 先假设都完成了
        On Error Resume Next ' 临时忽略文件检查错误
        For Each key In workerScripts.Keys ' <--- 现在 key 变量是之前声明的那个
            ' 检查此 Worker 是否已处理
            If Not processedWorkers.Exists(key) Then ' <--- 现在 processedWorkers 已经被 Set
                Dim markerFilePath As String
                markerFilePath = workerScripts(key)

                If fso.fileExists(markerFilePath) Then
                    ' 标记文件存在，尝试处理结果文件
                    resultsFilePath = mainWorkbookPath & "\~Results_" & key & ".csv" ' 构造结果文件路径

                    If fso.fileExists(resultsFilePath) Then
                        ' 结果文件也存在，处理它
                        ' 处理结果文件并将结果存入字典
                        resultData = ProcessResultFile(resultsFilePath)
                        ' --- 修改: 检查 ProcessResultFile 是否返回错误 ---
                        If IsError(resultData) Then
                            Debug.Print "Worker " & key & ": 处理结果文件时出错."
                            ws.Cells(CInt(key) + 1, "D").Value = "错误: 读取结果失败"
                            processedWorkers.Add key, False ' 标记为处理失败
                        ElseIf Not IsEmpty(resultData) Then
                             ' --- 修改: 只添加到 Results_Map ---
                            Results_Map.Add key, resultData ' 将结果存入字典
                            processedWorkers.Add key, True ' 标记为成功处理
                            Debug.Print "Worker " & key & ": 结果已读入内存."
                        Else
                            ' 文件有效但为空
                            Debug.Print "Worker " & key & ": 结果文件为空或无效."
                            ws.Cells(CInt(key) + 1, "D").Value = "注意: 无结果数据"
                            processedWorkers.Add key, True ' 标记为已处理 (即使无数据)
                        End If
                        ' --- 移除对 workerResults 的引用 ---
                        ' If Not IsEmpty(resultData) Then
                        '     workerResults.Add key, resultData ' 将结果存入字典，以worker编号为键 <--- 删除
                        ' End If
                        ' processedWorkers.Add key, True ' <--- 已移入上面的条件判断
                        ' Debug.Print "Worker " & key & ": 结果已处理." ' <--- 已移入上面的条件判断
                    Else
                        ' 标记文件存在，但结果文件丢失
                        Debug.Print "Worker " & key & " 完成，但结果文件未找到: " & resultsFilePath
                        ws.Cells(CInt(key) + 1, "D").Value = "错误: 结果文件丢失"
                        processedWorkers.Add key, False
                    End If
                Else
                    ' 标记文件不存在，此 Worker 尚未完成
                    allWorkersFinished = False
                    ' 不需要 Exit For，继续检查其他 Worker
                End If

                If Err.Number <> 0 Then
                    Debug.Print "检查/处理 Worker " & key & " 时发生错误: " & Err.Description
                    Err.Clear
                    allWorkersFinished = False ' 出错则认为未完成
                    If Not processedWorkers.Exists(key) Then processedWorkers.Add key, False ' 标记为处理失败
                End If
            End If ' End If Not processedWorkers.Exists(key)
        Next ' key
        On Error GoTo ErrorHandler ' 恢复错误处理

        ' 检查是否所有 Worker 都已被处理 (无论成功或失败)
        If processedWorkers.Count = workerScripts.Count Then
            allWorkersFinished = True ' 所有 Worker 都已处理完毕
            Exit Do
        End If

        ' --- 超时检查 (代码不变) ---
        If Timer - waitStartTime > timeoutSeconds Then
            MsgBox "等待 Worker 超时 (" & timeoutSeconds & "秒)！可能部分 Worker 未能正常完成或结果未处理。", vbExclamation
            allWorkersFinished = False ' 标记为未全部成功完成
            Exit Do
        End If

        ' --- 使用 Timer 和 DoEvents 暂停 (代码不变) ---
        pauseUntil = Timer + 1
        Do While Timer < pauseUntil
            DoEvents
        Loop

    Loop

    ' --- 所有 Worker 处理完成或超时后，执行清理 ---
    If allWorkersFinished And processedWorkers.Count = workerScripts.Count Then
        ws.Range("A1").Value = "主线程: 所有 Worker 完成并处理完毕，正在清理..."
    ElseIf processedWorkers.Count < workerScripts.Count Then
         ws.Range("A1").Value = "主线程: 等待超时，部分 Worker 未完成，正在清理..."
    Else ' processedWorkers.Count = workerScripts.Count 但 allWorkersFinished = False (说明有错误)
         ws.Range("A1").Value = "主线程: 所有 Worker 完成但部分结果处理失败，正在清理..."
    End If
    Application.StatusBar = "正在清理临时文件..."
    Call CleanupWorkerFiles(fso, mainWorkbookPath, numberOfWorkers) ' 清理所有临时文件

    Application.StatusBar = False
    ws.Range("A1").Value = "主线程: 完成 (总耗时: " & Format(Timer - startTime, "0.00") & "s)"
    MsgBox processedWorkers.Count & " 个 Worker 任务已尝试处理并清理。" & vbCrLf & _
           "总耗时: " & Format(Timer - startTime, "0.00") & " 秒", vbInformation

Cleanup:
    On Error Resume Next
    Application.StatusBar = False
    Application.Interactive = originalInteractiveState ' 恢复原始交互状态
    Application.ScreenUpdating = True ' 恢复屏幕更新
    Set ws = Nothing
    Set fso = Nothing
    Set wsh = Nothing
    Set workerScripts = Nothing
    Set processedWorkers = Nothing ' <--- 释放新字典
    Exit Sub

ErrorHandler:
    MsgBox "发生错误: " & Err.Description, vbCritical, "错误"
    ' 不直接 Resume Cleanup，而是先恢复状态再跳转
    Application.StatusBar = False
    Application.Interactive = originalInteractiveState ' 确保错误时也恢复交互状态
    Application.ScreenUpdating = True ' 确保错误时也恢复屏幕更新
    Resume Cleanup ' 跳转到清理代码
End Sub

' --- (修改后) 工作宏：执行查询并写入结果文件 ---
' (这个宏内容与你上次提供的已修改版本一致，包含了写入 CSV 的逻辑)
Public Sub RunWorkerLog(nWorker As Integer, mainWorkbookName As String)
    Dim mainWB As Workbook
    Dim mainWS As Worksheet
    Dim oXL As Object ' Excel Application
    ' Dim queryID As String ' 不再需要
    ' Dim resultValue As String ' 不再需要
    ' Dim i As Long ' 不再需要
    Dim startTime As Double
    Dim endTime As Double
    Dim duration As Double
    Dim logRow As Long
    Dim resultsFilePath As String
    Dim mainWorkbookPath As String

    ' --- ADODB Example Variables (保持不变) ---
    ' Dim conn As Object ' ADODB.Connection
    ' Dim rs As Object   ' ADODB.Recordset
    ' Dim connectionString As String
    ' Dim sqlQuery As String
    ' Dim resultsArray As Variant ' To hold data from recordset
    ' Dim fileNum As Integer ' For writing file

    On Error GoTo WorkerErrorHandler

    logRow = nWorker + 1

    ' --- 获取主 Excel 实例和工作簿/表 (代码不变) ---
    Set oXL = GetObject(, "Excel.Application")
    If oXL Is Nothing Then GoTo WorkerCleanup
    Set mainWB = oXL.Workbooks(mainWorkbookName)
    If mainWB Is Nothing Then GoTo WorkerCleanup
    mainWorkbookPath = mainWB.Path
    Set mainWS = mainWB.Sheets("Sheet1")
    If mainWS Is Nothing Then GoTo WorkerCleanup

    ' --- 记录启动日志 (代码不变) ---
    startTime = Timer
    On Error Resume Next
    mainWS.Cells(logRow, "B").Value = "Worker " & nWorker & ": 开始查询, " & Format(Now, "hh:mm:ss")
    On Error GoTo WorkerErrorHandler

    ' --- 构造结果文件名 ---
    resultsFilePath = mainWorkbookPath & "\~Results_" & nWorker & ".csv"

    ' --- 实际数据库查询逻辑 (替换模拟代码 - 不变) ---
    ' ... (ADODB code placeholder) ...

    ' --- 模拟查询和获取结果 (代码不变) ---
    Application.Wait Now + TimeValue(SIMULATED_QUERY_TIME)
    
    ' 模拟查询结果数据
    Dim resultsArray() As Variant
    ReDim resultsArray(1 To 10, 1 To 3) ' 预分配10行数据空间
    
    ' 记录实际使用的行数
    Dim currentRow As Long
    currentRow = 0
    
    ' 模拟生成查询结果数据
    Dim i As Long
    For i = 1 To 5 ' 假设每个worker生成5条记录
        currentRow = currentRow + 1
        resultsArray(currentRow, 1) = "Worker" & nWorker & "_" & Format(i, "000")
        resultsArray(currentRow, 2) = "测试数据" & i
        resultsArray(currentRow, 3) = Format(Now, "yyyy-mm-dd hh:mm:ss")
    Next i
    
    ' 调整数组大小以匹配实际数据量
    If currentRow > 0 Then
        ReDim Preserve resultsArray(1 To currentRow, 1 To 3)
    End If

    ' --- 将结果写入 CSV 文件 ---
    If currentRow > 0 Then
        Debug.Print "Worker " & nWorker & ": Attempting to write data to " & resultsFilePath
        Call WriteArrayToCsv(resultsFilePath, resultsArray) ' <--- 调用写入 CSV 函数
        ' Check if file exists after attempting write (basic check)
        Dim fsoCheck As Object
        Set fsoCheck = CreateObject("Scripting.FileSystemObject")
        If Not fsoCheck.fileExists(resultsFilePath) Then
            Err.Raise vbObjectError + 513, "RunWorkerLog", "WriteArrayToCsv called but result file not found: " & resultsFilePath
        End If
        Set fsoCheck = Nothing
    Else
        ' 创建空文件表示无结果
        Debug.Print "Worker " & nWorker & ": No data generated, creating empty file: " & resultsFilePath
        Dim fsoTemp As Object
        Set fsoTemp = CreateObject("Scripting.FileSystemObject")
        On Error Resume Next ' Temporarily ignore error during empty file creation
        fsoTemp.CreateTextFile resultsFilePath, True
        If Err.Number <> 0 Then
             ' Raise error if even empty file creation fails
             Dim errMsg As String
             errMsg = "Failed to create empty result file: " & resultsFilePath & " Error: " & Err.Description
             Err.Clear
             Err.Raise vbObjectError + 514, "RunWorkerLog", errMsg
        End If
        On Error GoTo WorkerErrorHandler ' Restore main error handler
        Set fsoTemp = Nothing
    End If

    ' --- (可选) 记录完成日志到主表 (代码不变) ---
    endTime = Timer
    duration = endTime - startTime
    On Error Resume Next
    mainWS.Cells(logRow, "C").Value = "Worker " & nWorker & ": 完成查询, 耗时: " & Format(duration, "0.00") & "s"
    On Error GoTo WorkerErrorHandler

WorkerCleanup:
    On Error Resume Next
    ' --- Release ADODB objects if used ---
    ' Set rs = Nothing
    ' Set conn = Nothing
    ' --- Release Excel objects ---
    Set mainWS = Nothing
    Set mainWB = Nothing
    Set oXL = Nothing
    Exit Sub ' 正常退出，VBScript 会继续创建标记文件

WorkerErrorHandler:
    ' ... (错误处理 - 不变) ...
    Resume WorkerCleanup
End Sub

' --- 新增辅助函数：将二维数组写入 CSV 文件 ---
' (这个函数内容与你上次提供的已修改版本一致)
Private Sub WriteArrayToCsv(filePath As String, dataArray As Variant)
    Dim fileNum As Integer
    Dim fso As Object
    Dim ts As Object ' TextStream
    Dim i As Long, j As Long
    Dim lineStr As String

    On Error GoTo WriteCsvError

    Set fso = CreateObject("Scripting.FileSystemObject")
    ' True = Overwrite if exists, True = Unicode (or False for ASCII)
    Set ts = fso.CreateTextFile(filePath, True, False)

    ' VBA 数组通常是 (列, 行) 或 (行, 列)，取决于如何获取
    ' GetRows 返回 (列, 行)，所以需要转置或按列优先写入
    ' 假设 dataArray 是 (行, 列) - 如果是 GetRows, 需要调整循环
    For i = LBound(dataArray, 1) To UBound(dataArray, 1) ' Iterate rows
        lineStr = ""
        For j = LBound(dataArray, 2) To UBound(dataArray, 2) ' Iterate columns
            ' Handle potential commas or quotes in data
            Dim cellValue As String
            cellValue = CStr(dataArray(i, j))
            If InStr(cellValue, ",") > 0 Or InStr(cellValue, """") > 0 Then
                cellValue = """" & Replace(cellValue, """", """""") & """"
            End If
            If j > LBound(dataArray, 2) Then lineStr = lineStr & ","
            lineStr = lineStr & cellValue
        Next j
        ts.WriteLine lineStr
    Next i

    ts.Close

WriteCsvExit:
    On Error Resume Next
    Set ts = Nothing
    Set fso = Nothing
    Exit Sub

WriteCsvError:
    ' --- 修改: 记录错误并重新引发，以便调用者知道失败 ---
    Dim errDesc As String
    errDesc = "Error writing CSV file '" & filePath & "': Error #" & Err.Number & " - " & Err.Description
    Debug.Print errDesc ' Log error to Immediate Window
    ' --- 重新引发错误，将错误传递给 RunWorkerLog ---
    Err.Raise Err.Number, "WriteArrayToCsv", errDesc
    ' --- 下面的 Resume 不会执行，因为错误已被重新引发 ---
    ' Resume WriteCsvExit ' <--- 删除或注释掉这行
End Sub


' --- 辅助函数：写入文本文件 (代码不变) ---
Private Sub WriteTextFile(fso As Object, filePath As String, content As String)
    Dim ts As Object ' TextStream
    On Error Resume Next
    If fso.fileExists(filePath) Then fso.DeleteFile filePath, True
    Set ts = fso.CreateTextFile(filePath, True) ' True = Overwrite if exists
    If Err.Number = 0 Then
        ts.Write content
        ts.Close
        Set ts = Nothing
    Else
        MsgBox "无法写入文件: " & filePath & vbCrLf & Err.Description, vbCritical
    End If
    On Error GoTo 0
End Sub

' --- (修改后) 清理宏 ---
' (这个宏内容与你上次提供的已修改版本一致，包含了清理 .csv)
Sub CleanupWorkerFiles(fso As Object, folderPath As String, Optional numberOfWorkersHint As Integer = 0)
    ' 参数 fso 和 folderPath 由调用者传入，避免重复创建
    ' numberOfWorkersHint 只是为了让文件名模式更精确一点，可选
    Dim f As Object ' File
    Dim filePattern As String
    Dim workerPatternBase As String

    If fso Is Nothing Or folderPath = "" Then Exit Sub

    On Error Resume Next ' 忽略清理过程中的错误

    ' 根据提示构建更精确的模式，否则使用通用模式
    If numberOfWorkersHint > 0 Then
        workerPatternBase = "~Worker_" & numberOfWorkersHint & "_*"
    Else
        workerPatternBase = "~Worker_*"
    End If

    ' 删除工作簿副本 (.xlsm)
    filePattern = workerPatternBase & ".xlsm"
    For Each f In fso.GetFolder(folderPath).Files
        If LCase(f.Name) Like LCase(filePattern) Then f.Delete True
    Next

    ' 删除 VBS 脚本 (.vbs)
    filePattern = workerPatternBase & ".vbs"
    For Each f In fso.GetFolder(folderPath).Files
        If LCase(f.Name) Like LCase(filePattern) Then f.Delete True
    Next

    ' 删除标记文件 (.tmp)
    filePattern = workerPatternBase & MARKER_FILE_EXT
    For Each f In fso.GetFolder(folderPath).Files
        If LCase(f.Name) Like LCase(filePattern) Then f.Delete True
    Next

    ' *** 新增：删除结果文件 (.csv) ***
    filePattern = "~Results_" & IIf(numberOfWorkersHint > 0, Right(workerPatternBase, Len(workerPatternBase) - 1), "*") & ".csv" ' Adjust pattern if needed
    ' More robust pattern if workerPatternBase is just "~Worker_*"
    If workerPatternBase = "~Worker_*" Then filePattern = "~Results_*.csv"
    ' If workerPatternBase is like "~Worker_N_*", use:
    ' filePattern = "~Results_" & Right(workerPatternBase, Len(workerPatternBase)-1) & ".csv" ' This might be too specific if N changes
    ' Safest might be just "~Results_*.csv" if numberOfWorkersHint isn't reliable for result files
    filePattern = "~Results_*.csv" ' Use a simple pattern for results files

    For Each f In fso.GetFolder(folderPath).Files
        If LCase(f.Name) Like LCase(filePattern) Then
            f.Delete True
        End If
    Next

    Set f = Nothing
End Sub


' --- (修改后) 辅助函数：处理单个结果文件，返回数据数组 ---
Private Function ProcessResultFile(resultsFilePath As String) As Variant ' <--- 改为 Function, 返回 Variant
    Dim fileNum As Integer
    Dim lineFromFile As String
    Dim lineItems As Variant
    Dim allLines As Collection ' 用于临时存储所有行数据
    Dim dataArray() As Variant ' 最终返回的二维数组
    Dim numRows As Long, numCols As Long
    Dim i As Long, j As Long

    On Error GoTo ProcessError

    Set allLines = New Collection
    numCols = -1 ' 初始化列数

    fileNum = FreeFile()
    Open resultsFilePath For Input As #fileNum

    Do While Not EOF(fileNum)
        Line Input #fileNum, lineFromFile
        lineItems = Split(lineFromFile, ",") ' 基础 CSV 分割

        If UBound(lineItems) >= 0 Then
            allLines.Add lineItems ' 将分割后的数组添加到集合
            If numCols = -1 Then numCols = UBound(lineItems) ' 获取列数 (从0开始)
        End If
    Loop
    Close #fileNum
    fileNum = 0 ' 重置

    ' --- 将 Collection 转换为二维数组 ---
    numRows = allLines.Count
    If numRows > 0 And numCols >= 0 Then
        ReDim dataArray(1 To numRows, 1 To numCols + 1) ' Redim 为 (行, 列)
        For i = 1 To numRows
            lineItems = allLines(i) ' 获取集合中的行数组
            For j = 0 To UBound(lineItems) ' 遍历列
                 If j <= numCols Then ' 防止数据行长度不一致导致越界
                    dataArray(i, j + 1) = lineItems(j) ' 填充到二维数组
                 End If
            Next j
        Next i
        ProcessResultFile = dataArray ' <--- 返回填充好的数组
    Else
        ProcessResultFile = Empty ' <--- 如果文件为空或无数据，返回 Empty
    End If

ProcessExit:
    Set allLines = Nothing
    Exit Function

ProcessError:
    Debug.Print "Error processing results file '" & resultsFilePath & "': " & Err.Description
    If fileNum > 0 Then Close #fileNum
    Set allLines = Nothing
    ProcessResultFile = CVErr(xlErrValue) ' 返回错误值，调用方可以检查
    Resume ProcessExit ' 使用 Resume 避免错误处理中的错误
End Function
